package cn.zfs.datasource.aop;

import cn.zfs.datasource.advice.GlobalException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@SuppressWarnings({"LambdaParameterTypeCanBeSpecified", "ImplicitArrayToString", "AlibabaClassMustHaveAuthor", "PointcutMethodStyleInspection"})
@Aspect
@Component
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(* cn.zfs.datasource.controller..*.*(..)))")
    public void controllerLogPointCut() {
        logger.info("初始化controller切点");
    }

    @Around("controllerLogPointCut()")
    public Object controllerLogAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            throw new GlobalException("系统出现异常");
        }
        HttpServletRequest request = attributes.getRequest();
        logger.info("请求路径url={}", request.getRequestURL().toString());
        logger.info("{}.{} 的请求参数 {}", joinPoint.getTarget().getClass().getName(),
                joinPoint.getSignature().getName(), JSONObject.toJSON(request.getParameterMap()));
        Object[] args = joinPoint.getArgs();
        Arrays.asList(args).forEach(arg -> arg = arg == null || StringUtils.isBlank(String.valueOf(arg)) ? null : arg);
        Object obj = joinPoint.proceed(args);
        logger.info("请求结果:{}", JSONObject.toJSONString(obj));
        return obj;
    }
}
